/**
 * 
 */
package com.roc.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roc.bean.MerinfoDetail;
import com.roc.dao.DaoException;
import com.roc.dao.IAgentDao;
import com.roc.dao.IBaseDao;
import com.roc.dao.IMerchantDao;
import com.roc.dao.ISQLBaseDao;
import com.roc.dao.ISysLogDao;
import com.roc.dao.IorgDao;
import com.roc.dao.impl.ITerminalDaoImpl;
import com.roc.newPage.IPageDao;
import com.roc.pojo.MerinfoChange;
import com.roc.pojo.Operators;
import com.roc.pojo.TblEditMchtInf;
import com.roc.pojo.TblMchtBankAccount;
import com.roc.pojo.TblMchtBizDeal;
import com.roc.pojo.TblMchtBizFee;
import com.roc.pojo.TblMchtInf;
import com.roc.pojo.TblMchtPicture;
import com.roc.pojo.TblTermInf;
import com.roc.pojo.TblTermRiskCfg;
import com.roc.service.IMerchantChangeServices;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.AuditingType;
import com.roc.util.constant.ConfigMerinfoUtil;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author
 * @date 2016年11月21日上午11:45:18
 */
@Service
@Transactional(rollbackFor = { ServiceException.class })
public class MerchantChangeServiceImpl implements IMerchantChangeServices {

    static Logger logger = LogManager.getLogger(MerchantChangeServiceImpl.class);

    @Autowired
    private IMerchantDao merchantDao;

    @Autowired
    private IBaseDao baseDao;

    @Autowired
    private IPageDao pageDao;

    @Autowired
    private ITerminalDaoImpl terminalDao;

    @Autowired
    private ISysLogDao sysLogDao;

    @Autowired
    ISQLBaseDao sqlBaseDao;

    @Autowired
    IorgDao orgDao;

    @Autowired
    private IAgentDao agentDao;


    @Override
    public MerinfoChange queryMerinfoChangeById(Long id) throws ServiceException {
        // TODO Auto-generated method stub
        MerinfoChange merinfo = null;
        Object[] param={id};
        try {
            String mer_hql=" from MerinfoChange t where t.id=?";
            merinfo=(MerinfoChange)pageDao.createQueryUniqueResult(mer_hql,param );
        } catch (DaoException e) {
            logger.error("查询商户变更信息变更失败", e);
            throw new ServiceException("查询商户信息变更失败");
        }
        return merinfo;
    }

    @Transactional(readOnly=true)
    public TblMchtInf queryMerinfoDetailInfo(String merinfoNo, boolean showName,String rkType )
                    throws ServiceException {
            TblMchtInf mer_info=null;
             
             Object[] param={merinfoNo};
             try {
                    if(null==merinfoNo) return mer_info; //为空返回
                    
                    //商户信息
                    String mer_hql=" from TblMchtInf t where t.id=?";
                    mer_info=(TblMchtInf)pageDao.createQueryUniqueResult(mer_hql,param );
                    if(null!=rkType && !rkType.equals("1")){
                            String cardNo=mer_info.getCertifNo();//证件号屏蔽
                            mer_info.setCertifNo(cardNo.substring(0,3)+"****"+cardNo.substring(cardNo.length()-4));//证件号
                    }
                    
                    String phone=mer_info.getContactPhoneNo();//手机号屏蔽
                    //mer_info.setContactPhoneNo(phone.substring(0, 3)+"****"+phone.substring(phone.length()-4));//手机号
                    mer_info.setContactPhoneNo(phone);
                    if(showName){//根据code显示名称
                            mer_info.setCertifType(ConfigMerinfoUtil.getCertifType(mer_info.getCertifType()));//证件类型
                            mer_info.setProvCd(ConfigMerinfoUtil.getGBProviceName(mer_info.getProvCd()));//省份
                            mer_info.setCityCd(ConfigMerinfoUtil.getGBCityName(mer_info.getCityCd()));//城市
                            mer_info.setAreaCd(ConfigMerinfoUtil.getGBAreaName(mer_info.getAreaCd()));//地区
                            
                            
                            //查询进件人员(后期可放入与商户联查，提高页面响应速度)
                            String q_sql="SELECT T.REAL_NAME FROM T_OPERATORS T WHERE T.ID=?";
                            Object[] params_1={mer_info.getRecUpdOpr()};
                            Object op_name=pageDao.findObj(q_sql, params_1);
                            mer_info.setRecUpdOpr(String.valueOf(op_name));
                    }
                     
                    //终端信息
                    String ter_hql="from TblTermInf t where t.id.MchtCd=?";
                    List<?> objList_ter=pageDao.queryAll(ter_hql, param);
                    if(null!=objList_ter && objList_ter.size()>0){
                            List<TblTermInf> terList=new ArrayList<TblTermInf>();
                            for (Object object : objList_ter) {
                                    TblTermInf terminfo=(TblTermInf)object;
                                    if(showName){
                                            terminfo.setTermTp(ConfigMerinfoUtil.getPosType(terminfo.getTermTp()));//获取终端类型具体名称
                                    }
                                    //查询终端风控信息
                                    String risk_hql="from TblTermRiskCfg t where t.id.MchtCd=? and t.id.TermId=?";
                                     Object[] param_risk={merinfoNo,terminfo.getId().getTermId()};
                                    List<?> objList_risk=pageDao.queryAll(risk_hql, param_risk);
                                    if(null!=objList_risk && objList_risk.size()>0){
                                            List<TblTermRiskCfg> riskList=new ArrayList<TblTermRiskCfg>();
                                            for (Object risk : objList_risk) {
                                                    TblTermRiskCfg fee=(TblTermRiskCfg)risk;
                                                    riskList.add(fee);
                                            }
                                            terminfo.setRiskCfgList(riskList); //set 终端风控信息
                                    }
                                    terList.add(terminfo);
                            }
                            mer_info.setTerminfoList(terList);//set终端
                            TblTermRiskCfg  tmpTb= new TblTermRiskCfg();
                            tmpTb.setAccpetStartTime(terList.get(0).getRiskCfgList().get(0).getAccpetStartTime());
                            tmpTb.setAccpetEndTime(terList.get(0).getRiskCfgList().get(0).getAccpetEndTime());
                            mer_info.setTerminfoRisk(tmpTb);//获取营业时间
                    }
                    //产品信息
                    String del_hql="select t.prodCd,t.transCd from  TblMchtBizDeal t where t.mchtCd=?";
                    List<?> objList_del=pageDao.queryAll(del_hql, param);
                    if(null!=objList_del && objList_del.size()>0){
                            List<TblMchtBizDeal> delList=new ArrayList<TblMchtBizDeal>();
                            String[] produdctArrayStr=new String[objList_del.size()];
                            int i=0;
                            Iterator<?> iter=objList_del.iterator();
                            while(iter.hasNext()){
                                    Object[] obj=(Object[])iter.next();
                                    TblMchtBizDeal terminfo=new TblMchtBizDeal();
                                    terminfo.setProdCd(String.valueOf(obj[0]));
                                    terminfo.setTransCd(String.valueOf(obj[1]));
                                    delList.add(terminfo);
                                    produdctArrayStr[i]=terminfo.getTransCd();
                                    i++;
                            }
                             
                            mer_info.setBizDelList(delList); //产品集合
                            mer_info.setProductStrs(produdctArrayStr);//产品
                            String[] productCodeStr=queryMchtBizDealArray(merinfoNo, true,showName);
                            mer_info.setProductCode(productCodeStr); //保存当前商户所选择的业务模式、t0/t1
                    }
                    
                    
                    //结算信息
                    String settle_hql="from TblMchtBankAccount t where t.ownerCd=?";
                    TblMchtBankAccount bankAccount=(TblMchtBankAccount)pageDao.createQueryUniqueResult(settle_hql,param );
                    //String account=bankAccount.getAccount();
                    //bankAccount.setAccount(account.substring(0, 4)+"****"+account.substring(account.length()-4));
                    //bankAccount.setAccount(account);
                    mer_info.setBankAccount(bankAccount);//SET 结算信息
                    
                    
                    //手续费
                    String fees_hql="select mchtCd,prodCd,bizCd,subBizCd,mchtFeePercent,mchtFeePctMax from TblMchtBizFee t where t.mchtCd=? order by t.subBizCd asc"; 
                    List<?> objList_fee=pageDao.queryAll(fees_hql, param);
                    if(null!=objList_fee && objList_fee.size()>0){
                            List<TblMchtBizFee> feeList=new ArrayList<TblMchtBizFee>();
                            Iterator<?> iter=objList_fee.iterator();
                            while(iter.hasNext()){
                                    Object[] obj=(Object[])iter.next();
                                    if(!(ConfigMerinfoUtil.ZPAY_FUNCTION_Z.equals(obj[1]) || ConfigMerinfoUtil.WPAY_FUNCTION_Z.equals(obj[1]) 
                							|| ConfigMerinfoUtil.WPAY_FUNCTION_F.equals(obj[1]))){
                                    if(obj[3].equals(ConfigMerinfoUtil.T0_2004_FUNCTION) || 
                                            obj[3].equals(ConfigMerinfoUtil.T0_2005_FUNCTION)){//t0 划付手续费  跳过
                                            continue;
                                    }
                                    TblMchtBizFee fee=new TblMchtBizFee();
                                    fee.setMchtCd(String.valueOf(obj[0]));
                                    fee.setProdCd(String.valueOf(obj[1]));
                                    fee.setBizCd(String.valueOf(obj[2]));
                                    fee.setSubBizCd(String.valueOf(obj[3]));
                                    if((obj[4])!=null)
                                    {
                                            fee.setMchtFeePercent(Double.parseDouble(String.valueOf((obj[4]))));
                                    }
                                    if((obj[5])!=null)
                                    {
                                            fee.setMchtFeePctMax(Double.parseDouble(String.valueOf((obj[5]))));
                                    }
                                    if(showName){
                                            String name="";
                                            if(fee.getProdCd().equals(ConfigMerinfoUtil.T1_FUNCTION)){
                                                    name="T1";
                                            }else if(fee.getProdCd().equals(ConfigMerinfoUtil.T0_FUNCTION)){
                                                    name="T0";
                                            }else if(ConfigMerinfoUtil.UNIONPAY_FUNCTION.equals(fee.getProdCd())){
            									name = "银联";
            								}else if(ConfigMerinfoUtil.ZWPAY_FUNCTION.equals(fee.getProdCd())){
            									name = "支付宝微信";
            								}
                                            String feeCodeName = ConfigMerinfoUtil.getFeeList(String.valueOf(obj[3])); //根据code 显示手续费名称
            								fee.setMchtFeeMd(name + (feeCodeName == null ? "" : feeCodeName)); 
                                    }
                                    feeList.add(fee); 
                               }
                            }
                            mer_info.setFee(feeList); //set手续费集合
                    }
                    //图片信息
                    String pic_hql="select t.Url,t.DocType  from TblMchtPicture t where t.MchtCd=? order by t.Pcode ASC ";
                    List<?> objList_pic=pageDao.queryAll(pic_hql, param);
                    if(null!=objList_pic && objList_pic.size()>0){
                            List<TblMchtPicture> picList=new ArrayList<TblMchtPicture>();
                            Iterator<?> iter=objList_pic.iterator();
                            while(iter.hasNext()){
                                    Object[] obj=(Object[])iter.next();
                                    TblMchtPicture picture=new TblMchtPicture();
                                    picture.setUrl(String.valueOf(obj[0]));
                                    picList.add(picture); 
                            }
                            mer_info.setPictrueList(picList);//图片路径地址
                    }
                    
                    return  mer_info;
            } catch (DaoException e) {
                     logger.error(e.getMessage(),e);
                     throw new ServiceException("--查询商户["+merinfoNo+"]详情失败",e);
            }
    }
    /**
     * 根据商户号查询结算周期
     * @param  mid 商户号
     * @param  type 是否正式表
     * @param  showName 是否显示名称
     * */
    @Transactional(readOnly=true)
    public String[] queryMchtBizDealArray(String mid,boolean type,boolean showName) throws ServiceException {
            String tableName="TBL_EDIT_MCHT_BIZ_DEAL";
            if(type){
                    tableName="TBL_MCHT_BIZ_DEAL";
            }
            String sql="SELECT DISTINCT T.PROD_CD FROM "+tableName+" T WHERE T.MCHT_CD=? ORDER BY T.PROD_CD ASC";
            List<String> productArray = new ArrayList<String>();
            try {
            	Object[] params={mid};
    			List<?> list=pageDao.querySqlAll(sql,params);
    			Iterator<?> iter=list.iterator();
    			while (iter.hasNext()) {
    				Object obj=iter.next();
    				if(!showName){
    					productArray.add(obj.toString());
    				}else{
    					if(obj.toString().equals("1000")){
    						productArray.add("T1");
    					}else if(obj.toString().equals("1171")){
    						productArray.add("T0");
    					}else if(obj.toString().equals("1191")){
    						productArray.add("银联扫码");
    					}else if(obj.toString().equals("1391")){
    						productArray.add("支付宝微信扫码");
    					}
    				}
    			}
            } catch (DaoException e) {
                    logger.error("----查询商户号["+mid+"]结算周期出错-----",e);
                    throw new ServiceException("----查询商户号["+mid+"]结算周期出错-----",e);
            }
            String[] returnStr= (String[])productArray.toArray(new String[productArray.size()]);
    		return returnStr;
    }

    @Override
    public List<MerinfoChange> queryC2List(String minDate, String maxDate) throws ServiceException {
        List<MerinfoChange> merinfoChanges = new ArrayList<MerinfoChange>();
        List<Object> objList = new ArrayList<Object>();
        
        StringBuffer sb = new StringBuffer();
        sb.append(" select M.Mid, A.NAME_BUSI,M.Bank_Account_Name,M.Bank_Account,M.Open_Bank, M.Bank_Code,M.Pub_Or_Pri, M.Dt_Auditor_Time,T.Real_Name,");
        sb.append(" (select O.Real_Name from T_OPERATORS O where o.id=t.oneagentid),");
        sb.append(" (select O.Real_Name from T_OPERATORS O where o.id=t.Companyid)");
        sb.append(" FROM T_MERINFO_CHANGE M");
        sb.append(" LEFT JOIN TBL_MCHT_INF A ON m.MID = A.MCHT_CD");
        sb.append(" LEFT JOIN t_operators T ON A.ext1 = T.ID");
        sb.append(" WHERE M.STATUS = 'Y'");
        sb.append(" AND M.DEAL_CODE = 'C2'");
        if(Constance.isNotEmpty(minDate)&&Constance.isNotEmpty(maxDate)){ //倒出时间
            sb.append("AND M.DT_AUDITOR_TIME >= TO_TIMESTAMP('" + minDate + "','YYYY-MM-DD') " );
            sb.append("AND M.DT_AUDITOR_TIME <= TO_TIMESTAMP('" + maxDate + "','YYYY-MM-DD') + 1 " );
        }
        sb.append(" ORDER BY M.Dt_Auditor_Time Asc");
      
        try {
                objList = sqlBaseDao.queryAll(sb.toString());
                if (objList != null && objList.size() > 0) {
                        Iterator<?> iterator = objList.iterator();
                        while (iterator.hasNext()) {
                                MerinfoChange merinfoChange = new MerinfoChange();
                                Object[] obj = (Object[]) iterator.next();
                                
                                merinfoChange.setMid((String) obj[0]);//商户号
                                merinfoChange.setNameBusi((String) obj[1]);//商户简称
                                merinfoChange.setBankAccountName((String) obj[2]);//账户名称
                                merinfoChange.setBankAccount((String) obj[3]);//
                                merinfoChange.setOpenBank((String) obj[4]);
                                merinfoChange.setBankCode((String) obj[5]);
                                merinfoChange.setPubOrPri((String) obj[6]);
                                merinfoChange.setDtAuditorTime((Date) obj[7]);//审核通过时间
                                merinfoChange.setUrl1((String) obj[8]);//直属代理商
                                merinfoChange.setUrl2((String) obj[9]);//一级代理商
                                merinfoChange.setUrl3((String) obj[10]);//所属大区
                                
                                merinfoChanges.add(merinfoChange);
                        }
                }
        } catch (DaoException e) {
                logger.error(e.getMessage(), e);
                throw new ServiceException(e.getMessage());
        }
        return merinfoChanges;
    }


}